﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using KTFrameworkCus;

using System.IO;
using System.Data;
using System.Xml;
using System.Text.RegularExpressions;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Security.Cryptography;
using System.Text;
using System.Net;
using System.Net.Mail;
using System.Collections;

/// <summary>
/// Summary description for dmsFunction
/// </summary>
public class dmsFunction : IDisposable
{
    void IDisposable.Dispose() { }
    static KTFrameworkCusEntities dcc = new KTFrameworkCusEntities();

    public dmsFunction()
    {
        //
        // TODO: Add constructor logic here
        //

    }

    public static string GetLanguage(string strVN, string strEN)
    {
        var currentLanguage = "vi-VN";
        if (HttpContext.Current.Session != null)
        {
            currentLanguage = HttpContext.Current.Session["language"] == null ? "vi-VN" : HttpContext.Current.Session["language"].ToString();
        }

        switch (currentLanguage)
        {
            case "vi-VN":
                return strVN;
            case "en-US":
                return strEN;
            default:
                return strVN;
        }
    }

    public static string getOriParent(int catid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        int parentidval = getCategoryByCateID(catid).ParentID.Value;
        if (parentidval == 113 || parentidval == 114)
        {
            return catid.ToString();
        }
        else
        {
            return getOriParent(parentidval);
        }
    }

    public udv_Users getUserByUserName(string username)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_Users.Where(t => t.UserName == username).FirstOrDefault();
    }

    public IEnumerable<udv_comment> getCommentbyParent(int parentid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_comment.Where(t => t.ReplyOn == parentid && t.isApproved == true);
    }

    public IEnumerable<udv_comment> getCommentsByProductID(int postid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_comment.Where(t => t.ProductID == postid && t.isApproved == true && t.ReplyOn == 0);
    }

    public bool SendMailBySmtp(string body, string mailnhan, string tieude, string emailfrom, string name)
    {
        try
        {

            MailMessage mail = new MailMessage();
            mail.From = new MailAddress(emailfrom, name);
            mail.To.Add(mailnhan);
            mail.Subject = tieude;
            mail.Body = body;
            mail.BodyEncoding = System.Text.Encoding.UTF8;
            mail.IsBodyHtml = true;
            SmtpClient mySmtpClient = new SmtpClient();
            mySmtpClient.Host = "smtp.gmail.com";
            mySmtpClient.Port = 587;
            mySmtpClient.Credentials = new System.Net.NetworkCredential("dmsvn2@gmail.com", "choemxin");
            mySmtpClient.EnableSsl = true;
            mySmtpClient.Send(mail);
            return true;

        }
        catch (Exception)
        {
            return false;
        }
    }


    public static IEnumerable<udv_Categories> getAllDuAnCategory()
    {
        return dmsFunction.getAllCategoriesByCat(239).OrderByDescending(t => t.AddedDate);
    }

    public static IEnumerable<udv_Products> getAllDuAn()
    {
        return dmsFunction.getAllProductByCat(239).Concat(dmsFunction.getAllProductByCat(214));
    }

    //public static void addToIIRF(string seourl, string aspxurl)
    //{
    //    TextWriter tw = new StreamWriter(Globals.ApplicationPath + "IIRF.INI");
    //    // RewriteRule  ^/trang-chu.html /Default.aspx       
    //    tw.WriteLine("RewriteRule  ^/" + seourl + " /" + aspxurl);
    //    tw.Close();
    //}

    //public static void deleteComments(bool isProduct, int id)
    //{
    //    using (KTFrameworkCusEntities dc = new KTFrameworkCusEntities())
    //    {
    //        IEnumerable<udv_comment> _danhsach;
    //        if (isProduct == true)
    //        {
    //            _danhsach = dc.udv_comment.Where(t => t.productid == id).ToList();
    //        }
    //        else
    //        {
    //            _danhsach = dc.udv_comment.Where(t => t.articleid == id).ToList();
    //        }

    //        foreach (var item in _danhsach)
    //        {
    //            dc.DeleteObject(item);
    //            dc.SaveChanges();
    //        }
    //    }
    //}

    public static IEnumerable<udv_Products> getProductByManufacturerID(int manuid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        var list = dc.udv_Products.Include("udv_Manufacturer").Where(t => t.udv_Manufacturer.ManufacturerID != 29 && t.IsActive == true).OrderByDescending(t => t.AddedDate);
        return list.Where(t => t.udv_Manufacturer.ManufacturerID == manuid);
    }

    public static IEnumerable<udv_Categories> getRootCategory()
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_Categories.Where(t => t.ParentID == 113 || t.ParentID == 114 && t.IsActive == true).Concat(dc.udv_Categories.Where(t => t.CateID == 114)).OrderBy(t => t.DisplayOrder);
    }

    public static IEnumerable<udv_Categories> getCategoryByParent(int parentid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_Categories.Where(t => t.ParentID == parentid && t.IsActive == true).OrderBy(t => t.DisplayOrder);
    }

    public static IEnumerable<udv_ProductImages> getProductImagesbyProductID(int pid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_ProductImages.Where(t => t.ProductID == pid).OrderBy(t => t.DisplayOrder);
    }

    public static IEnumerable<udv_ArticleImages> getArticleImagesbyArticleID(int aid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_ArticleImages.Where(t => t.ArticleID == aid).OrderBy(t => t.DisplayOrder);
    }

    public static IEnumerable<CategoryImage> getCategoryImagesbyCategoryID(int cid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.CategoryImage.Where(t => t.CategoryID == cid).OrderBy(t => t.DisplayOrder);
    }

    public static string ConvertPlayer(string inSource)
    {
        int mediaID = 1;
        string outSource = inSource;
        string pattern = @"<object(.*?)codebase(.*?)>(.*?)</object>";
        MatchCollection outputs = Regex.Matches(inSource, pattern, RegexOptions.IgnoreCase);
        foreach (Match item in outputs)
        {
            string pattern2 = "src=['|\"](?<url>.*?)['|\"]";
            string VideoSrc = Regex.Match(item.Value, pattern2, RegexOptions.IgnoreCase).Value.Replace("/UserUpload", "UserUpload").Replace("\"", "").Replace("src=", "");
            StringBuilder sb = new StringBuilder();
            sb.Append("<object classid='clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' height='320' id='single" + mediaID + "' name='single" + mediaID + "' width='470'><param name='movie' value='" + Globals.ApplicationPath + "Controls/longtaivideo/player.swf' /><param name='allowfullscreen' value='true' /><param name='allowscriptaccess' value='always' /><param name='wmode' value='transparent' /><param name='flashvars' value='file=" + (Globals.ApplicationPath + VideoSrc) + "' /><embed allowfullscreen='true' allowscriptaccess='always' bgcolor='#000000' flashvars='file=" + (Globals.ApplicationPath + VideoSrc) + "' height='320' id='single" + (mediaID + 1) + "' name='single" + (mediaID + 1) + "' src='" + Globals.ApplicationPath + "Controls/longtaivideo/player.swf' width='470'></embed></object>");
            outSource = outSource.Replace(item.Value, sb.ToString());
            mediaID = mediaID + 2;
        }

        return outSource;
    }

    public static string generateLinkForGallery(string catAlbumid)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbums.xml"));
        XmlNode xNode = xmldoc.SelectSingleNode("dms/album[@id='" + catAlbumid + "']");
        return "thu-vien/" + dmsFunction._ConvertToUnSign(xNode["title"].InnerText, "-") + "," + xNode.Attributes["id"].Value + ",chi-tiet.html";
    }

    public static string generateLinkForGalleryCategory(string cateid)
    {
        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));
        XmlNode xNode = xmldoc.SelectSingleNode("dms/category[@id='" + cateid + "']");
        return "thu-vien/" + dmsFunction._ConvertToUnSign(xNode["title"].InnerText, "-") + "," + xNode.Attributes["id"].Value + ".html";
    }

    public static string getUrl(string seourl, string aspxurl)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        if (dc.Setting.Where(t => t.Name == "EnableUrlRewrite").FirstOrDefault().Value == "1")
        {
            return seourl;
        }
        else
        {
            return aspxurl;
        }
    }

    public static string getSEOUrlExtension()
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.Setting.Where(t => t.Name == "UrlExtension").FirstOrDefault().Value;
    }

    static string seourl = "";
    public static string GenerateSEOUrlForCategory(int catid)
    {
        try
        {
            KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
            udv_Categories _udvcat1 = dc.udv_Categories.Where(t => t.CateID == catid).FirstOrDefault();

            seourl = _ConvertToUnSign(_udvcat1.Title, "-") + "," + _udvcat1.CateID + getSEOUrlExtension();
            if (_udvcat1.ParentID.Value != 0)
            {
                AddtoCategorySEOUrl(_udvcat1.ParentID.Value);
            }


            return seourl;
        }
        catch (Exception)
        {
            return seourl;
        }
    }


    public static string GenerateSEOUrl(int id, bool isProduct)
    {
        try
        {
            KTFrameworkCusEntities dc = new KTFrameworkCusEntities();

            if (isProduct == true)
            {
                udv_Products _udvP = dc.udv_Products.Include("udv_categories").Where(t => t.ProductID == id).FirstOrDefault();
                if (_udvP != null)
                {
                    seourl = _ConvertToUnSign(_udvP.Title, "-") + "," + _udvP.ProductID + ",chi-tiet" + getSEOUrlExtension();
                    AddtoCategorySEOUrl(_udvP.udv_Categories.CateID);
                }
            }
            else
            {
                udv_Articles _udvA = dc.udv_Articles.Include("udv_categories").Where(t => t.ArticleID == id).FirstOrDefault();
                if (_udvA != null)
                {
                    seourl = _ConvertToUnSign(_udvA.Title, "-") + "," + _udvA.ArticleID + ",chi-tiet" + getSEOUrlExtension();
                    AddtoCategorySEOUrl(_udvA.udv_Categories.CateID);
                }
            }

            return seourl;
        }
        catch (Exception)
        {
            return seourl;
        }
    }

    public static void AddtoCategorySEOUrl(int catid)
    {
        udv_Categories _udvcat1 = dcc.udv_Categories.Where(t => t.CateID == catid).FirstOrDefault();
        seourl = _ConvertToUnSign(_udvcat1.Title, "-") + "/" + seourl;
        if (_udvcat1.ParentID.Value != 0)
        { 
            AddtoCategorySEOUrl(_udvcat1.ParentID.Value); 
        }

    }



    public static udv_Categories getCategoryByCateID(int cateid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        return dc.udv_Categories.Where(t => t.CateID == cateid).FirstOrDefault();
    }

    public static bool isLangVN()
    {
        if (HttpContext.Current.Session["language"] != null)
        {
            if (HttpContext.Current.Session["language"].ToString() == "vi-VN")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }

    public static DataTable GetAlbumCategories()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("CateID");
        dt.Columns.Add("Title");
        dt.Columns.Add("Title_en");
        dt.Columns.Add("Order", typeof(Int32));

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbumCategory.xml"));
        XmlNodeList nodelist = xmldoc.SelectNodes("dms/category");
        foreach (XmlNode item in nodelist)
        {
            DataRow dr = dt.NewRow();
            dr[0] = item.Attributes["id"].Value;
            dr[1] = item["title"].InnerText;
            dr[2] = item["title_en"].InnerText;
            dr[3] = item["order"].InnerText;
            dt.Rows.Add(dr);

        }

        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = "Order ASC";
        data = dv.ToTable();
        return data;
    }

    public static void bindSelectedMenu(HiddenField hd1, HiddenField hd2, HiddenField hd3, int cat1)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        hd1.Value = cat1.ToString();
        if (dc.udv_Categories.Where(t => t.CateID == cat1).FirstOrDefault() != null && dc.udv_Categories.Where(t => t.CateID == cat1).FirstOrDefault().ParentID != null)
        {
            int cat2 = dc.udv_Categories.Where(t => t.CateID == cat1).FirstOrDefault().ParentID.Value;
            hd2.Value = cat2.ToString();

            if (dc.udv_Categories.Where(t => t.CateID == cat2).FirstOrDefault() != null && dc.udv_Categories.Where(t => t.CateID == cat2).FirstOrDefault().ParentID != null)
            {
                hd3.Value = dc.udv_Categories.Where(t => t.CateID == cat2).FirstOrDefault().ParentID.Value.ToString();
                //int cat2 = dc.udv_Categories.Where(t => t.CateID == cat1).FirstOrDefault().CateID;
            }
        }
    }

    public static DataTable GetAllAlbumByCategory(string catei)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("AlbumID");
        dt.Columns.Add("Title");
        dt.Columns.Add("ImageUrl");
        dt.Columns.Add("Description");
        dt.Columns.Add("order", typeof(Int32));
        dt.Columns.Add("Title_en");
        dt.Columns.Add("Description_en");

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbums.xml"));
        XmlNodeList nodelist = xmldoc.SelectNodes("dms/album");
        foreach (XmlNode item in nodelist)
        {
            if (item["lock"].InnerText == "0")
            {
                if (item.Attributes["category"].Value == catei)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = item.Attributes["id"].Value;
                    dr[1] = item["title"].InnerText;
                    dr[2] = KTFrameworkCus.Globals.ApplicationPath + "dms/Albums/" + item["poster"].InnerText;
                    dr[3] = item["description"].InnerText;
                    dr[4] = item["order"].InnerText;
                    dr[5] = item["title_en"].InnerText;
                    dr[6] = item["description_en"].InnerText;
                    dt.Rows.Add(dr);
                }
            }

        }
        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = "order ASC";
        data = dv.ToTable();
        return data;
    }

    public static DataTable GetAllAlbum()
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("AlbumID");
        dt.Columns.Add("Title");
        dt.Columns.Add("ImageUrl");
        dt.Columns.Add("Description");
        dt.Columns.Add("order", typeof(Int32));
        dt.Columns.Add("Title_en");
        dt.Columns.Add("Description_en");
        dt.Columns.Add("AddedDate", typeof(DateTime));

        XmlDocument xmldoc = new XmlDocument();
        xmldoc.Load(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsAlbums.xml"));
        XmlNodeList nodelist = xmldoc.SelectNodes("dms/album");
        foreach (XmlNode item in nodelist)
        {
            if (item["lock"].InnerText == "0")
            {
                DataRow dr = dt.NewRow();
                dr[0] = item.Attributes["id"].Value;
                dr[1] = item["title"].InnerText;
                dr[2] = KTFrameworkCus.Globals.ApplicationPath + "dms/Albums/" + item["poster"].InnerText;
                dr[3] = item["description"].InnerText;
                dr[4] = item["order"].InnerText;
                dr[5] = item["title_en"].InnerText;
                dr[6] = item["description_en"].InnerText;
                dr[7] = item["addedDate"].InnerText;
                dt.Rows.Add(dr);
            }

        }
        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = "order ASC";
        data = dv.ToTable();
        return data;
    }

    public static DataTable getImagesInAlbum(string albumid)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("ImageUrl");
        dt.Columns.Add("ImageUrlThumb");
        dt.Columns.Add("Title");
        dt.Columns.Add("Title_en");
        dt.Columns.Add("Description");
        dt.Columns.Add("Description_en");
        dt.Columns.Add("Url");
        dt.Columns.Add("Order", typeof(Int32));
        dt.Columns.Add("id", typeof(Int32));

        XmlDocument xdoc = new XmlDocument();
        xdoc.Load(HttpContext.Current.Server.MapPath(KTFrameworkCus.Globals.ApplicationPath + "dms/dmsImages.xml"));
        XmlNodeList nodelist = xdoc.SelectNodes("dms/image[@albumid='" + albumid + "']");
        foreach (XmlNode item in nodelist)
        {
            if (item["active"].InnerText == "1")
            {
                DataRow dr = dt.NewRow();
                dr[0] = KTFrameworkCus.Globals.ApplicationPath + "dms/Images/f/" + item["fullimage"].InnerText;
                dr[1] = KTFrameworkCus.Globals.ApplicationPath + "dms/Images/t/" + item["thumbimage"].InnerText;
                dr[2] = item["title"].InnerText;
                dr[3] = item["title_en"].InnerText;
                dr[4] = item["description"].InnerText;
                dr[5] = item["description_en"].InnerText;
                dr[6] = item["url"].InnerText;
                dr[7] = item["order"].InnerText;
                dr[8] = item.Attributes["id"].Value;
                dt.Rows.Add(dr);
            }

        }
        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = "order ASC";
        data = dv.ToTable();
        return data;
    }


    public static bool deleteImage(string path)
    {
        try
        {
            FileInfo TheFile = new FileInfo(path);
            if (TheFile.Exists)
            {
                File.Delete(path);
                return true;
            }
            return false;
        }
        catch (Exception)
        {
            return false;
        }

    }

    public static bool moveImage(string pathtofile, string pathtosave)
    {
        try
        {
            string sourceFile = pathtofile;
            string destinationFile = pathtosave;
            System.IO.File.Move(sourceFile, destinationFile);
            return true;
        }
        catch (Exception ex)
        {
            return false;
        }
    }

    static IEnumerable<udv_Articles> _udvResult;
    public static IEnumerable<udv_Articles> getAllArticleByCat(int catid)
    {

        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        //_udvPro = null;
        _udvResult = dc.udv_Articles.Include("udv_categories").Where(t => t.ArticleID == 99999999);
        loadArticlebyCate(catid);
        return _udvResult.OrderByDescending(t => t.AddedDate).ToList();
    }

    protected static IEnumerable<udv_Articles> loadArticlebyCate(int caid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        IEnumerable<udv_Articles> _IEProList = dc.udv_Articles.Include("udv_categories").Where(t => t.udv_Categories.CateID == caid);
        //IEnumerable<udv_Articles> _IEProList = from c in dc.udv_Articles where c.udv_Categories.CateID == caid select c;
        if (_IEProList.Count() > 0)
        {
            _udvResult = _udvResult.Concat(_IEProList);
        }
        IEnumerable<udv_Categories> _IECatList = dc.udv_Categories.Where(c => c.ParentID == caid);
        if (_IECatList.Count() > 0)
        {
            foreach (var item in _IECatList)
            {
                loadArticlebyCate(item.CateID);
            }
        }
        return _udvResult;

    }

    static IEnumerable<udv_Categories> _udvResult2;
    public static IEnumerable<udv_Categories> getAllCategoriesByCat(int catid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        //_udvPro = null;
        _udvResult2 = dc.udv_Categories.Where(t => t.CateID == 99999999);
        loadCategorybyCate(catid);
        return _udvResult2.Where(t => t.IsActive == true).OrderBy(t => t.DisplayOrder).ToList();
    }

    protected static IEnumerable<udv_Categories> loadCategorybyCate(int caid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        IEnumerable<udv_Categories> _IEProList = dc.udv_Categories.Where(t => t.ParentID == caid);
        //IEnumerable<udv_Articles> _IEProList = from c in dc.udv_Articles where c.udv_Categories.CateID == caid select c;
        if (_IEProList.Count() > 0)
        {
            _udvResult2 = _udvResult2.Concat(_IEProList);
        }
        IEnumerable<udv_Categories> _IECatList = dc.udv_Categories.Where(c => c.ParentID == caid);
        if (_IECatList.Count() > 0)
        {
            foreach (var item in _IECatList)
            {
                loadCategorybyCate(item.CateID);
            }
        }
        return _udvResult2;

    }


    static IEnumerable<udv_Products> _udvResult1;
    public static IEnumerable<udv_Products> getAllProductByCat(int catid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        //_udvPro = null;
        _udvResult1 = dc.udv_Products.Include("udv_categories").Where(t => t.ProductID == 99999999);
        loadProductbyCate(catid);
        return _udvResult1.Where(t => t.IsActive == true).OrderByDescending(t => t.AddedDate).ToList();
    }

    protected static IEnumerable<udv_Products> loadProductbyCate(int caid)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        IEnumerable<udv_Products> _IEProList = dc.udv_Products.Include("udv_categories").Where(t => t.udv_Categories.CateID == caid && (t.ParentID == null || t.ParentID == 0));
        //IEnumerable<udv_Products> _IEProList = from c in dc.udv_Products where c.udv_Categories.CateID == caid select c;
        if (_IEProList.Count() > 0)
        {
            _udvResult1 = _udvResult1.Concat(_IEProList);
        }
        IEnumerable<udv_Categories> _IECatList = dc.udv_Categories.Where(c => c.ParentID == caid);
        if (_IECatList.Count() > 0)
        {
            foreach (var item in _IECatList)
            {
                loadProductbyCate(item.CateID);
            }
        }
        return _udvResult1;

    }


    public string getDayOfWeek(object dtt)
    {
        DateTime dt = Convert.ToDateTime(dtt);
        string thu = dt.DayOfWeek.ToString();
        switch (thu)
        {
            case ("Monday"):
                return "Hai";

            case ("Tuesday"):
                return "Ba";

            case ("Wednesday"):
                return "Tư";

            case ("Thursday"):
                return "Năm";

            case ("Friday"):
                return "Sáu";

            case ("Saturday"):
                return "Bảy";

            default:
                return "Chủ Nhật";

        }

    }

    public static string strCutString(string str, int limit)
    {
        string strRe = "";
        str = _Strip(str);
        //
        // Split string on spaces.
        // ... This will separate all the words.
        //
        string[] words = str.Split(' ');
        int i = 0;
        foreach (string word in words)
        {
            if (i <= limit)
                strRe += word + " ";
            i++;
        }
        if (words.Count() > limit)
            strRe += "...";
        return strRe;
    }

    public static string _Strip(string text)
    {
        try
        {
            return HttpContext.Current.Server.HtmlDecode(Regex.Replace(text, @"<(.|\n)*?>", string.Empty));
        }
        catch (Exception)
        {

            return text;
        }

    }

    public static string _ConvertToUnSign(string text, string splitter)
    {
        for (int i = 33; i < 48; i++)
        {
            text = text.Replace(((char)i).ToString(), "");
        }

        for (int i = 58; i < 65; i++)
        {
            text = text.Replace(((char)i).ToString(), "");
        }
        for (int i = 91; i < 97; i++)
        {
            text = text.Replace(((char)i).ToString(), "");
        }

        for (int i = 123; i < 127; i++)
        {
            text = text.Replace(((char)i).ToString(), "");
        }
        text = text.Replace(" ", splitter);
        Regex regex = new Regex(@"\p{IsCombiningDiacriticalMarks}+");
        string strFormD = text.Normalize(System.Text.NormalizationForm.FormD);
        return regex.Replace(strFormD, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
    }

    public static DataTable _SortDatatable(DataTable dt, string sortExpression)
    {
        DataTable data = new DataTable();
        DataTable tblEmployees = dt;
        DataView dv = tblEmployees.DefaultView;
        dv.Sort = sortExpression;
        data = dv.ToTable();
        return data;
    }

    public static bool _checkLanguage()
    {
        if (HttpContext.Current.Session["language"] != null)
        {
            if (HttpContext.Current.Session["language"].ToString() == "vi-VN")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        else
        {
            return true;
        }
    }

    public static DataTable RemoveDuplicateRows(DataTable dTable, string colName)
    {
        Hashtable hTable = new Hashtable();
        ArrayList duplicateList = new ArrayList();

        foreach (DataRow drow in dTable.Rows)
        {
            if (hTable.Contains(drow[colName]))
                duplicateList.Add(drow);
            else
                hTable.Add(drow[colName], string.Empty);
        }

        foreach (DataRow dRow in duplicateList)
            dTable.Rows.Remove(dRow);

        return dTable;
    }

    public static DataTable _Search(string kww, bool includeProducts, bool includeArticles, bool includeCategory)
    {
        KTFrameworkCusEntities dc = new KTFrameworkCusEntities();
        string kw = kww;
        DataTable dt = new DataTable();
        dt.Columns.Add("id");
        dt.Columns.Add("title");
        dt.Columns.Add("title_en");
        dt.Columns.Add("imageurl");
        dt.Columns.Add("description");
        dt.Columns.Add("description_en");
        dt.Columns.Add("AddedDate", typeof(DateTime));
        dt.Columns.Add("type");
        dt.Columns.Add("seourl");

        if (includeArticles == true)
        {
            IEnumerable<udv_Articles> _listArticles;
            if (_checkLanguage())
            {
                _listArticles = from c in dc.udv_Articles where c.TitleForSearch.ToLower().Contains(kw) || c.AbstractForSearch.ToLower().Contains(kw) select c;

            }
            else
            {
                _listArticles = (from c in dc.udv_Articles where c.Title_enForSearch.ToLower().Contains(kw) || c.Abstract_enForSearch.ToLower().Contains(kw) select c).ToList();

            }

            if (_listArticles.Count() > 0)
            {
                foreach (var item in _listArticles)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = item.ArticleID;
                    dr[1] = item.Title;
                    dr[2] = item.Title_en;
                    dr[3] = Globals.ApplicationPath + "UserUpload/Articles/" + item.ImageUrl;
                    dr[4] = _Strip(item.Body).Length > 150 ? _Strip(item.Body).Substring(0, 149) : _Strip(item.Body);
                    dr[5] = _Strip(item.Body_en != null ? item.Body_en : "").Length > 150 ? _Strip(item.Body_en != null ? item.Body_en : "").Substring(0, 149) : _Strip(item.Body_en != null ? item.Body_en : "");
                    dr[6] = item.AddedDate;
                    dr[7] = "a";
                    dr[8] = item.SEOUrl;
                    dt.Rows.Add(dr);
                }
            }
        }

        if (includeCategory == true)
        {
            IEnumerable<udv_Categories> _listCategories = (from c in dc.udv_Categories where c.IsActive == true select c).ToList();
            if (_listCategories.Count() > 0)
            {
                foreach (var item in _listCategories)
                {
                    if (_checkLanguage())
                    {
                        if (_ConvertToUnSign(item.Title.ToLower(), " ").Contains(kw) || _ConvertToUnSign(item.Description == null ? "" : item.Description.ToLower(), " ").Contains(kw))
                        {
                            DataRow dr = dt.NewRow();
                            dr[0] = item.CateID;
                            dr[1] = item.Title;
                            dr[2] = item.Title_en;
                            dr[3] = Globals.ApplicationPath + "UserUpload/" + item.ImageUrl;
                            dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                            dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                            dr[6] = item.AddedDate;
                            dr[7] = "c";
                            dr[8] = item.SEOUrl;
                            dt.Rows.Add(dr);
                        }

                        //foreach (string item1 in kw.Split(' '))
                        //{
                        //    if (_ConvertToUnSign(item.Title.ToLower(), " ").Contains(item1))
                        //    {
                        //        DataRow dr = dt.NewRow();
                        //        dr[0] = item.CateID;
                        //        dr[1] = item.Title;
                        //        dr[2] = item.Title_en;
                        //        dr[3] = Globals.ApplicationPath + "UserUpload/" + item.ImageUrl;
                        //        dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                        //        dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                        //        dr[6] = item.AddedDate;
                        //        dr[7] = "c";
                        //        dr[8] = item.SEOUrl;
                        //        dt.Rows.Add(dr);
                        //    }
                        //}

                    }
                    else
                    {
                        if (_ConvertToUnSign(item.Title_en.ToLower(), " ").Contains(kw) || _ConvertToUnSign(item.Description_en == null ? "" : item.Description_en.ToLower(), " ").Contains(kw))
                        {
                            DataRow dr = dt.NewRow();
                            dr[0] = item.CateID;
                            dr[1] = item.Title;
                            dr[2] = item.Title_en;
                            dr[3] = Globals.ApplicationPath + "UserUpload/" + item.ImageUrl;
                            dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                            dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                            dr[6] = item.AddedDate;
                            dr[7] = "c";
                            dr[8] = item.SEOUrl;
                            dt.Rows.Add(dr);
                        }

                        //foreach (string item2 in kw.Split(' '))
                        //{
                        //    if (_ConvertToUnSign(item.Title_en.ToLower(), " ").Contains(item2))
                        //    {
                        //        DataRow dr = dt.NewRow();
                        //        dr[0] = item.CateID;
                        //        dr[1] = item.Title;
                        //        dr[2] = item.Title_en;
                        //        dr[3] = Globals.ApplicationPath + "UserUpload/" + item.ImageUrl;
                        //        dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                        //        dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                        //        dr[6] = item.AddedDate;
                        //        dr[7] = "c";
                        //        dr[8] = item.SEOUrl;
                        //        dt.Rows.Add(dr);
                        //    }
                        //}
                    }

                }
            }
        }

        if (includeProducts == true)
        {
            IEnumerable<udv_Products> _listProducts;
            if (_checkLanguage())
            {
                _listProducts = (from c in dc.udv_Products where c.ParentID == 0 || c.ParentID == null && c.TitleForSearch.ToLower().Contains(kw) || c.DescriptionForSearch.ToLower().Contains(kw) select c).ToList();

            }
            else
            {
                _listProducts = (from c in dc.udv_Products where c.ParentID == 0 || c.ParentID == null && c.Title_enForSearch.ToLower().Contains(kw) || c.Description_enForSearch.ToLower().Contains(kw) select c).ToList();

            }

            if (_listProducts.Count() > 0)
            {
                foreach (var item in _listProducts)
                {
                    DataRow dr = dt.NewRow();
                    dr[0] = item.ProductID;
                    dr[1] = item.Title;
                    dr[2] = item.Title_en;
                    dr[3] = Globals.ApplicationPath + "UserUpload/Products/" + item.ImageUrl;
                    dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                    dr[5] = _Strip(item.Description_en).Length > 150 ? _Strip(item.Description_en).Substring(0, 149) : _Strip(item.Description_en);
                    dr[6] = item.AddedDate;
                    dr[7] = "p";
                    dr[8] = item.SEOUrl;
                    dt.Rows.Add(dr);
                }
            }
        }

        dt = RemoveDuplicateRows(dt, "title");
        DataTable data = _SortDatatable(dt, "AddedDate DESC");

        DataTable dt2 = data.Clone();
        // Find word by word
        if (includeArticles == true)
        {
            IEnumerable<udv_Articles> _list1 = dc.udv_Articles.ToList();
            foreach (var item in _list1)
            {
                if (_checkLanguage())
                {
                    foreach (string item1 in _ConvertToUnSign(item.Title.ToLower(), " ").Split(' '))
                    {
                        foreach (string item2 in kw.Split(' '))
                        {
                            if (item1 == item2)
                            {
                                DataRow dr = dt2.NewRow();
                                dr[0] = item.ArticleID;
                                dr[1] = item.Title;
                                dr[2] = item.Title_en;
                                dr[3] = Globals.ApplicationPath + "UserUpload/Articles/" + item.ImageUrl;
                                dr[4] = _Strip(item.Body).Length > 150 ? _Strip(item.Body).Substring(0, 149) : _Strip(item.Body);
                                dr[5] = _Strip(item.Body_en != null ? item.Body_en : "").Length > 150 ? _Strip(item.Body_en != null ? item.Body_en : "").Substring(0, 149) : _Strip(item.Body_en != null ? item.Body_en : "");
                                dr[6] = item.AddedDate;
                                dr[7] = "a";
                                dr[8] = item.SEOUrl;
                                dt2.Rows.Add(dr);
                            }
                        }
                    }
                }
                else
                {
                    foreach (string item1 in _ConvertToUnSign(item.Title_en.ToLower(), " ").Split(' '))
                    {
                        foreach (string item2 in kw.Split(' '))
                        {
                            if (item1 == item2)
                            {
                                DataRow dr = dt2.NewRow();
                                dr[0] = item.ArticleID;
                                dr[1] = item.Title;
                                dr[2] = item.Title_en;
                                dr[3] = Globals.ApplicationPath + "UserUpload/Articles/" + item.ImageUrl;
                                dr[4] = _Strip(item.Body).Length > 150 ? _Strip(item.Body).Substring(0, 149) : _Strip(item.Body);
                                dr[5] = _Strip(item.Body_en != null ? item.Body_en : "").Length > 150 ? _Strip(item.Body_en != null ? item.Body_en : "").Substring(0, 149) : _Strip(item.Body_en != null ? item.Body_en : "");
                                dr[6] = item.AddedDate;
                                dr[7] = "a";
                                dr[8] = item.SEOUrl;
                                dt2.Rows.Add(dr);
                            }
                        }
                    }
                }
            }
        }


        if (includeProducts == true)
        {
            IEnumerable<udv_Products> _list1 = dc.udv_Products.Where(t => t.ParentID == 0 || t.ParentID == null).ToList();
            foreach (var item in _list1)
            {
                if (_checkLanguage())
                {
                    foreach (string item1 in _ConvertToUnSign(item.Title.ToLower(), " ").Split(' '))
                    {
                        foreach (string item2 in kw.Split(' '))
                        {
                            if (item1 == item2)
                            {
                                DataRow dr = dt2.NewRow();
                                dr[0] = item.ProductID;
                                dr[1] = item.Title;
                                dr[2] = item.Title_en;
                                dr[3] = Globals.ApplicationPath + "UserUpload/Products/" + item.ImageUrl;
                                dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                                dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                                dr[6] = item.AddedDate;
                                dr[7] = "p";
                                dr[8] = item.SEOUrl;
                                dt2.Rows.Add(dr);
                            }
                        }
                    }
                }
                else
                {
                    foreach (string item1 in _ConvertToUnSign(item.Title_en.ToLower(), " ").Split(' '))
                    {
                        foreach (string item2 in kw.Split(' '))
                        {
                            if (item1 == item2)
                            {
                                DataRow dr = dt2.NewRow();
                                dr[0] = item.ProductID;
                                dr[1] = item.Title;
                                dr[2] = item.Title_en;
                                dr[3] = Globals.ApplicationPath + "UserUpload/Products/" + item.ImageUrl;
                                dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                                dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                                dr[6] = item.AddedDate;
                                dr[7] = "p";
                                dr[8] = item.SEOUrl;
                                dt2.Rows.Add(dr);
                            }
                        }
                    }
                }
            }
        }

        if (includeCategory == true)
        {
            IEnumerable<udv_Categories> _listCategories = (from c in dc.udv_Categories where c.IsActive == true select c).ToList();
            if (_listCategories.Count() > 0)
            {
                foreach (var item in _listCategories)
                {
                    if (_checkLanguage())
                    {
                        foreach (string item1 in _ConvertToUnSign(item.Title.ToLower(), " ").Split(' '))
                        {
                            foreach (string item2 in kw.Split(' '))
                            {
                                if (item1 == item2)
                                {
                                    DataRow dr = dt2.NewRow();
                                    dr[0] = item.CateID;
                                    dr[1] = item.Title;
                                    dr[2] = item.Title_en;
                                    dr[3] = Globals.ApplicationPath + "UserUpload/" + item.ImageUrl;
                                    dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                                    dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                                    dr[6] = item.AddedDate;
                                    dr[7] = "c";
                                    dr[8] = item.SEOUrl;
                                    dt2.Rows.Add(dr);
                                }
                            }
                        }
                    }
                    else
                    {
                        foreach (string item1 in _ConvertToUnSign(item.Title_en.ToLower(), " ").Split(' '))
                        {
                            foreach (string item2 in kw.Split(' '))
                            {
                                if (item1 == item2)
                                {
                                    DataRow dr = dt2.NewRow();
                                    dr[0] = item.CateID;
                                    dr[1] = item.Title;
                                    dr[2] = item.Title_en;
                                    dr[3] = Globals.ApplicationPath + "UserUpload/" + item.ImageUrl;
                                    dr[4] = _Strip(item.Description).Length > 150 ? _Strip(item.Description).Substring(0, 149) : _Strip(item.Description);
                                    dr[5] = _Strip(item.Description_en != null ? item.Description_en : "").Length > 150 ? _Strip(item.Description_en != null ? item.Description_en : "").Substring(0, 149) : _Strip(item.Description_en != null ? item.Description_en : "");
                                    dr[6] = item.AddedDate;
                                    dr[7] = "c";
                                    dr[8] = item.SEOUrl;
                                    dt2.Rows.Add(dr);
                                }
                            }
                        }
                    }
                }
            }
        }

        DataTable data2 = RemoveDuplicateRows(dt2, "title");
        data2 = _SortDatatable(data2, "AddedDate DESC");
        data.Merge(data2);
        return data;
    }



    public static DataTable TableThongKe()
    {
        DataTable dtb = new DataTable();
        // Khai báo chuỗi kết nối
        var conString = ConfigurationManager.ConnectionStrings["SqlServices"];
        string ConnectionString = conString.ConnectionString;

        SqlConnection Conn = new SqlConnection(ConnectionString);
        try
        {
            // Mở kết nối
            Conn.Open();
            DataSet ds = new DataSet();
            SqlCommand cmdUpd = new SqlCommand("spThongKe_Edit", Conn);
            cmdUpd.CommandType = CommandType.StoredProcedure;
            SqlDataAdapter da = new SqlDataAdapter(cmdUpd);
            // Đổ dữ liệu vào DataSet
            da.Fill(ds);
            dtb = ds.Tables[0];
        }
        catch { }
        finally
        {
            if (Conn.State == ConnectionState.Open)
                Conn.Close();
            Conn.Dispose();
        }
        return dtb;
    }

    public static int _getIntFromQueryString(string queryName, int def)
    {
        try
        {
            int catid = def;
            if (HttpContext.Current.Request.QueryString[queryName] != null)
            {
                catid = int.Parse(HttpContext.Current.Request.QueryString[queryName]);
            }
            return catid;
        }
        catch (Exception)
        {
            return def;
        }
    }

    public static string _getStringFromQueryString(string queryName, string def)
    {
        try
        {
            string qs = def;
            if (HttpContext.Current.Request.QueryString[queryName] != null)
            {
                qs = HttpContext.Current.Request.QueryString[queryName];
            }
            return qs;
        }
        catch (Exception)
        {
            return def;
        }
    }

    public string CreateRandomPassword(int PasswordLength)
    {
        string _allowedChars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz0123456789";
        Random randNum = new Random();
        string kq = "";
        for (int i = 0; i < PasswordLength; i++)
        {
            int t = randNum.Next(0, _allowedChars.Length);
            kq = kq + _allowedChars.Substring(t, 1);
        }
        return kq;
    }

    public static string Md5Hashing(string text)
    {
        MD5CryptoServiceProvider x = new MD5CryptoServiceProvider();
        byte[] bs = Encoding.UTF8.GetBytes(text);
        bs = x.ComputeHash(bs);
        StringBuilder sb = new StringBuilder();
        foreach (byte b in bs)
        {
            sb.Append(b.ToString("x2").ToUpper());
        }
        return sb.ToString();
    }

    public string GetIP()
    {
        string strHostName = "";
        strHostName = System.Net.Dns.GetHostName();

        IPHostEntry ipEntry = System.Net.Dns.GetHostEntry(strHostName);

        IPAddress[] addr = ipEntry.AddressList;

        return addr[addr.Length - 1].ToString();
    }

    public string IpAddress()
    {

        string ip;
        try
        {
            ip = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
            if (!string.IsNullOrEmpty(ip))
            {
                if (ip.IndexOf(",") > 0)
                {
                    string[] ipRange = ip.Split(',');
                    int le = ipRange.Length - 1;
                    ip = ipRange[le];
                }
            }
            else
            {
                ip = HttpContext.Current.Request.UserHostAddress;
            }
        }
        catch { ip = null; }

        return ip;
    }

    public string CurrentUrl
    {
        get
        {
            string strUrl = HttpContext.Current.Request.Url.ToString().Trim();
            return strUrl;
        }
    }

}